package com.hs.health.cloud.tars.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtils
{

    public static void formatMapDate( Map<String, Object> map, SimpleDateFormat sdf )
    {
        if ( map == null )
            return;
        Iterator<String> iterator = map.keySet().iterator();
        while ( iterator.hasNext() )
        {
            String key = iterator.next();
            Object value = map.get( key );
            if ( value instanceof Date )
            {
                map.put( key, sdf.format( value ) );
            }
        }
    }

    public static void formatMapDateToUnix( List<Map<String, Object>> list )
    {
        if ( list == null )
            return;
        for ( Map<String, Object> map : list )
        {
            formatMapDateToUnix( map );
        }
    }

    public static void formatMapDateToUnix( Map<String, Object> map )
    {
        if ( map == null )
            return;
        Iterator<String> iterator = map.keySet().iterator();
        while ( iterator.hasNext() )
        {
            String key = iterator.next();
            Object value = map.get( key );
            if ( value instanceof Date )
            {
                map.put( key, ( ( Date ) value ).getTime() / 1000 );
            }
        }
    }

    public static void formatMapDateToLong( List<Map<String, Object>> list )
    {
        if ( list == null )
            return;
        for ( Map<String, Object> map : list )
        {
            formatMapDateToLong( map );
        }
    }

    public static void formatMapDateToLong( Map<String, Object> map )
    {
        if ( map == null )
            return;
        Iterator<String> iterator = map.keySet().iterator();
        while ( iterator.hasNext() )
        {
            String key = iterator.next();
            Object value = map.get( key );
            if ( value instanceof Date )
            {
                map.put( key, ( ( Date ) value ).getTime() );
            }
        }
    }

    public static void formatMapDateToTime( Map<String, Object> map )
    {
        if ( map == null )
            return;
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        Iterator<String> iterator = map.keySet().iterator();
        while ( iterator.hasNext() )
        {
            String key = iterator.next();
            Object value = map.get( key );
            if ( value instanceof Date )
            {
                map.put( key, sdf.format( value ) );
            }
        }
    }

    public static void formatMapDateToTime( List<Map<String, Object>> list )
    {
        if ( list == null )
            return;
        for ( Map<String, Object> map : list )
        {
            formatMapDateToTime( map );
        }
    }

    /**
     * 计算两个日期之间相差的天数
     * 
     * @param smdate
     *            较小的时间
     * @param bdate
     *            较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween( Date smdate, Date bdate ) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        smdate = sdf.parse( sdf.format( smdate ) );
        bdate = sdf.parse( sdf.format( bdate ) );
        Calendar cal = Calendar.getInstance();
        cal.setTime( smdate );
        long time1 = cal.getTimeInMillis();
        cal.setTime( bdate );
        long time2 = cal.getTimeInMillis();
        long between_days = ( time2 - time1 ) / ( 1000 * 3600 * 24 );

        return Integer.parseInt( String.valueOf( between_days ) );
    }

    /**
     * 计算两个时间之间相差的分钟数
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     */
    public static int mininutsBetween( Date smdate, Date bdate ) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        smdate = sdf.parse( sdf.format( smdate ) );
        bdate = sdf.parse( sdf.format( bdate ) );
        Calendar cal = Calendar.getInstance();
        cal.setTime( smdate );
        long time1 = cal.getTimeInMillis();
        cal.setTime( bdate );
        long time2 = cal.getTimeInMillis();
        long between_mininuts = ( time2 - time1 ) / ( 1000 * 60 );

        return Integer.parseInt( String.valueOf( between_mininuts ) );
    }

    public static Date getSundayDate( Date date )
    {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime( date );
        calendar.setFirstDayOfWeek( Calendar.MONDAY );
        calendar.set( Calendar.DAY_OF_WEEK, Calendar.SUNDAY );
        calendar.set( Calendar.HOUR_OF_DAY, 0 );
        calendar.set( Calendar.MINUTE, 0 );
        calendar.set( Calendar.SECOND, 0 );
        return calendar.getTime();
    }

    /**
     * 判断两个日期之间过了几周
     * 
     * @return
     */
    public static int weekDistance( Date start, Date end )
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        int distance = 0;
        try
        {
            DateUtils dateUtils = new DateUtils();
            // 获取起始日期的周日的日期
            Date d1 = sdf.parse( formatDdate( getSundayDate( start ) ) );

            Date d2 = sdf.parse( formatDdate( getSundayDate( end ) ) );
            distance = new Long( ( d2.getTime() - d1.getTime() ) / 86400000 / 7 ).intValue();
        }
        catch ( ParseException e )
        {
            // TODO Auto-generated catch block
            LogUtils.error( e );
        }
        return distance;
    }

    public static Date getDateBefore( Date d, int day )
    {
        Calendar now = Calendar.getInstance();
        now.setTime( d );
        now.set( Calendar.DATE, now.get( Calendar.DATE ) - day );
        return now.getTime();
    }

    public static Date fromMdate( String mdate )
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        try
        {
            return sdf.parse( mdate );
        }
        catch ( ParseException e )
        {
            // TODO Auto-generated catch block
            LogUtils.error( e );
        }
        return null;
    }

    /**
     * 将HIS端返回的日期格式yyyyMMdd转化为Date类型
     * @param ddate
     * @return
     */
    public static Date fromHISDdate(String ddate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            return sdf.parse(ddate);
        } catch (Exception e) {
            LogUtils.error(e);
        }
        return null;
    }

    public static Date fromTime( String tdate )
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        try
        {
            return sdf.parse( tdate );
        }
        catch ( ParseException e )
        {
            // TODO Auto-generated catch block
            LogUtils.error( e );
        }
        return null;
    }

    /**
     * 将HIS返回的时间格式yyyyMMddHH:mm:ss转化为Date
     * @param tdate
     * @return
     */
    public static Date fromHISTime(String tdate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");
        try {
            return sdf.parse(tdate);
        } catch (Exception e) {
            LogUtils.error(e);
        }
        return null;
    }

    public static String getDateBefore( String mdate, int day )
    {
        Date d = fromMdate( mdate );
        if (d == null) {
            return null;
        }
        Calendar now = Calendar.getInstance();
        now.setTime( d );
        now.set( Calendar.DATE, now.get( Calendar.DATE ) - day );
        return formatDdate( now.getTime() );
    }

    public static Date getDateAfter( Date d, int day )
    {
        Calendar now = Calendar.getInstance();
        now.setTime( d );
        now.set( Calendar.DATE, now.get( Calendar.DATE ) + day );
        return now.getTime();
    }

    public static String formatMdate( Date date )
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM" );
        return sdf.format( date );
    }

    public static String formatDdate( Date date )
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        return sdf.format( date );
    }

    /**
     * 构造HIS格式yyyyMMdd的时间串
     * @param date
     * @return
     */
    public static String formatHISDdate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(date);
    }

    public static String formatTime( Date date )
    {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        return sdf.format( date );
    }

    /**
     * 构造HIS格式yyyyMMddHH:mm:ss的时间串
     * @param date
     * @return
     */
    public static String formatHISTime(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");
        return sdf.format(date);
    }

    public static String formatWNTime(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }

    /**
     * 将HIS的日期格式转化为Tars所需的日期格式
     * @param ddate yyyyMMdd
     * @return yyyy-MM-dd
     */
    public static String convertHISDateToTars(String ddate) {
        Date date = fromHISDdate(ddate);
        return formatDdate(date);
    }

    /**
     * 将HIS的时间格式转化为Tars所需的时间格式
     * @param tdate yyyyMMddHH:mm:ss
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String convertHISTimeToTars(String tdate) {
        Date date = fromHISTime(tdate);
        return formatTime(date);
    }

    /**
     * 将Tars的日期格式转化为HIS所需的日期格式
     * @param ddate yyyy-MM-dd
     * @return yyyyMMdd
     */
    public static String convertTarsDateToHIS(String ddate) {
        Date date = fromMdate(ddate);
        return formatHISDdate(date);
    }

    /**
     * 将Tars的时间格式转化为HIS所需的时间格式
     * @param tdate yyyy-MM-dd HH:mm:ss
     * @return yyyyMMddHH:mm:ss
     */
    public static String convertTarsTimeToHIS(String tdate) {
        Date date = fromTime(tdate);
        return formatHISTime(date);
    }

    /**
     * 将Tars的时间格式转化为WN所需的时间格式
     * @param tdate yyyy-MM-dd HH:mm:ss
     * @return yyyyMMddHHmmss
     */
    public static String convertTarsTimeToWN(String tdate) {
        Date date = fromTime(tdate);
        return formatWNTime(date);
    }

    public static int unixTime( Date date )
    {
        Long time = date.getTime() / 1000;
        return time.intValue();
    }

    public static void main( String[] args ) throws ParseException
    {
        System.err.println( new DateUtils().getCurrentMonday() );
        //		System.err.println(getDateBefore(new Date(), 1));
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // Date start = sdf.parse("2015-11-1");
        // Date end = sdf.parse("2015-11-09");
        // System.err.println(weekDistance(start, end));
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // Date today = new DateUtils().getStartTime();
        // System.out.println("today33" + new DateUtils().getDateBefore(today,
        // 12));
        // String previousMonday = new DateUtils().getPreviousMonday();
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // Date monday = sdf.parse(previousMonday);
        // Calendar cal = Calendar.getInstance();
        // cal.setTime(monday);
        // System.out.println(previousMonday);
        // cal.add(Calendar.DATE, 7);
        //
        // System.out.println(sdf.format(cal.getTime()));
    }

    // 用来全局控制 上一周，本周，下一周的周数变化

    public Date getStartTime()
    {
        Calendar cal = Calendar.getInstance();
        cal.set( Calendar.HOUR_OF_DAY, 0 );
        cal.set( Calendar.SECOND, 0 );
        cal.set( Calendar.MINUTE, 0 );
        cal.set( Calendar.MILLISECOND, 0 );
        return cal.getTime();
    }

    // 获得当前日期与本周一相差的天数
    private int getMondayPlus()
    {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = cd.get( Calendar.DAY_OF_WEEK );
        if ( dayOfWeek == 1 )
        {
            return -6;
        }
        else
        {
            return 2 - dayOfWeek;
        }
    }

    private int weeks = 0;

    // 获得上周星期一的日期
    public String getPreviousMonday()
    {
        weeks--;
        int mondayPlus = this.getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add( GregorianCalendar.DATE, mondayPlus + 7 * weeks );
        Date monday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
        String preMonday = df.format( monday );
        return preMonday;
    }

    // 获得本周星期一的日期
    public String getCurrentMonday()
    {
        weeks = 0;
        int mondayPlus = this.getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add( GregorianCalendar.DATE, mondayPlus );
        Date monday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
        String preMonday = df.format( monday );
        return preMonday;
    }

    // 获得下周星期一的日期
    public String getNextMonday()
    {
        weeks++;
        int mondayPlus = this.getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add( GregorianCalendar.DATE, mondayPlus + 7 * weeks );
        Date monday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
        String preMonday = df.format( monday );
        return preMonday;
    }

    public static Date getNextMoth( Date date )
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime( date );
        cal.add( Calendar.MONTH, 1 );
        cal.set( Calendar.DAY_OF_MONTH, 1 );
        return cal.getTime();
    }

    // 获得相应周的周日的日期
    public String getSunday()
    {
        int mondayPlus = this.getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add( GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6 );
        Date monday = currentDate.getTime();
        SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
        String preMonday = df.format( monday );
        return preMonday;
    }

    /**
     * 将yyyy-MM-dd'T'HH:mm:ss.SSS"格式的时间转化为Tars标准时间格式（时间格式不唯一）
     * @param ttime
     * @return
     */
    public static String convertReportTimeToTars(String ttime) {
        SimpleDateFormat sdf = null;
        //根据字符串长度判断格式
        if (ttime.length() == 19) {
            sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        } else {
            sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        }
        try {
            Date date = sdf.parse(ttime);
            return formatTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将yyyy-MM-dd'T'HH:mm:ss"格式的时间转化为Tars标准时间格式
     * @param ttime
     * @return
     */
    public static String convertReportTime2ToTars(String ttime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        try {
            Date date = sdf.parse(ttime);
            return formatTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
